<?php
// postReadings.php
include 'aggregate.php';
$mysqli = include 'dbiConnect.php';
echo "<pre>\n";
echo "Writing a file\n";
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$content = $_POST['content'];
$content = json_decode($content, TRUE);
$watts = $content['watts'];
$stmt = $mysqli->prepare("SELECT id FROM device WHERE mac = ?");
$stmt->bind_param('s', $content['mac']); 
$stmt->execute();
$stmt->bind_result($deviceId); 
$stmt->fetch();
fwrite($fh, $deviceId);
$stmt->close();
$raw = 'r';
// $mysqldate = date( 'Y-m-d H:i:s', $phpdate );
// $phpdate = strtotime( $mysqldate );
// http://www.richardlord.net/blog/dates-in-php-and-mysql
$now = date('Y-m-d H:i:s');
for ($i=0; $i<count($watts); $i++) {
    $var = (string)$i;
    $var = str_pad($var, 4, '0', STR_PAD_LEFT);
    $watt = $watts[$i];
    $stmt = $mysqli->prepare("INSERT INTO readings (device_id, variable, timestamp, timespan, value) VALUES (?, ?, ?, ?, ?)"); 
    $stmt->bind_param('isssd', $deviceId,$var,$now,$raw,$watt); 
    $stmt->execute();
    $stmt->close();
}
aggregateIfNewHour($mysqli, 'readings', $deviceId, $now);
$mysqli->close();
// $stringData = "Tracy Tanner\n";
// fwrite($fh, $stringData);
fwrite($fh, print_r($_POST,TRUE));
fwrite($fh, print_r($content,TRUE));
fclose($fh);
echo "Finished writing a file\n";
echo "</pre>\n";
?>
